package com.ruoyi.yn.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.yn.YnBusinessExceptions;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.yn.domain.YnRecycler;
import com.ruoyi.yn.domain.YnUserAddress;
import com.ruoyi.yn.domain.YnUserOrder;
import com.ruoyi.yn.mapper.YnRecyclerMapper;
import com.ruoyi.yn.mapper.YnUserAddressMapper;
import com.ruoyi.yn.util.LocationUtils;
import com.ruoyi.yn.vo.YnUserOrderVo;
import com.ruoyi.yn.mapper.YnUserOrderMapper;
import com.ruoyi.yn.service.IYnUserOrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户订单Service业务层处理
 *
 * @author Ming
 * @date 2023-04-25
 */
@Service
public class YnUserOrderServiceImpl extends ServiceImpl<YnUserOrderMapper, YnUserOrder> implements IYnUserOrderService {

    @Resource
    private YnUserAddressMapper addressMapper;

    @Resource
    private YnRecyclerMapper recyclerMapper;

    @Override
    public TableDataInfo<YnUserOrderVo> queryList(YnUserOrderVo entity) {
        return PageUtils.buildDataInfo(this.baseMapper.queryList(PageUtils.buildPage(), entity));
    }

    @Override
    public List<YnUserOrderVo> queryAll(YnUserOrderVo entity) {
        return this.baseMapper.queryList(entity);
    }

    @Override
    public YnUserOrderVo queryById(String id) {
        return this.baseMapper.queryById(id);
    }

    @Override
    public String recentRecyclers(String userAddressId) {
        String recyclerId = "";
        Double minDistance = null;
        YnUserAddress ynUserAddress = addressMapper.selectById(userAddressId);
        if (ObjectUtil.isEmpty(ynUserAddress)) {
            throw new YnBusinessExceptions("用户地址信息有误");
        }
        Double userLongitude = ynUserAddress.getLongitude();
        Double userLatitude = ynUserAddress.getLatitude();
        List<YnRecycler> recyclers = ChainWrappers.lambdaQueryChain(recyclerMapper).eq(YnRecycler::getDisable, "0")
                .select(YnRecycler::getId, YnRecycler::getLatitude, YnRecycler::getLongitude)
                .list();
        for (YnRecycler recycler : recyclers) {
            Long longitude = recycler.getLongitude();
            Long latitude = recycler.getLatitude();
            double distance = LocationUtils.calculateDistanceM(userLongitude, userLatitude, longitude, latitude);
            if (minDistance == null) {
                minDistance = distance;
            } else {
                if (distance < minDistance) {
                    minDistance = distance;
                    recyclerId = recycler.getId();
                }
            }
        }
        return recyclerId;
    }
}
